package cv.ltq.studentesdemo.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Highlight;
import co.elastic.clients.elasticsearch.core.search.HighlightField;
import co.elastic.clients.elasticsearch.core.search.Hit;
import cv.ltq.studentesdemo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

@Controller
public class StudentController {
    @Autowired
    ElasticsearchClient client;

    @GetMapping("/searchHightLight")
    public String searchHightLight(){
        return "searchHightLight";
    }

    @PostMapping("/searchHightLight")//根据关键字查询并高亮显示
    public ModelAndView search(String keyword) throws IOException {
        System.out.println("keyword"+keyword);
        List<Student>list=new ArrayList<>();

        Query queryName=new Query.Builder()
                .match(new MatchQuery.Builder()
                        .field("name").query(keyword)
                        .build())
                .build();


        SearchRequest searchRequest=new SearchRequest.Builder()
                .highlight(new Highlight.Builder()
                        .fields("name",new HighlightField.Builder()
                                .postTags("</font>")
                                .preTags("<font color='red'>").build())
                        .build())
                .index("student")
                .query(queryName)
                .build();
        SearchResponse<Student>search=client.search(searchRequest, Student.class);
        for (Hit<Student> hit:search.hits().hits()){
          Student student=hit.source();
          String name=hit.highlight().get("name").get(0);
          student.setName(name);
          list.add(student);
          System.out.println(hit.source());
        }

        ModelAndView mv=new ModelAndView();
        mv.addObject("students",list);
        mv.setViewName("student");
        return mv;
    }

}
